<template>
  <div class="reviews-container">
    <h1>书评中心</h1>
    <div v-for="comment in comments" :key="comment.comment_id" class="comment-card">
      <div class="comment-header">
        <el-avatar :src="comment.reader.avatar" />
        <span class="username">{{ comment.reader.username }}</span>
        <span class="novel-title">评论了《{{ comment.novel.novel_name }}》</span>
      </div>
      <div class="comment-content">{{ comment.content }}</div>
      <div class="comment-footer">
        <el-button size="small" @click="likeComment(comment)">
          <el-icon><CaretTop /></el-icon> 点赞 ({{ comment.likes }})
        </el-button>
        <el-button size="small" @click="handleEdit(comment)" v-if="canEdit(comment)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(comment.comment_id)" v-if="canDelete(comment)">删除</el-button>
      </div>
    </div>

    <el-pagination
      @current-change="fetchComments"
      :current-page="currentPage"
      :page-size="pageSize"
      layout="prev, pager, next"
      :total="totalElements">
    </el-pagination>

    <el-dialog title="编辑评论" v-model="editDialogVisible">
      <el-input type="textarea" v-model="editingComment.content"></el-input>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import request from '@/utils/request';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useAuth } from '@/composables/useAuth';

import { CaretTop } from '@element-plus/icons-vue';

const comments = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const totalElements = ref(0);

const editDialogVisible = ref(false);
const editingComment = ref({});

const { user } = useAuth();

const fetchComments = async (page = 1) => {
  try {
    const response = await request.get('/public/comments', { params: { page, size: pageSize.value } });
    comments.value = response.content;
    totalElements.value = response.totalElements;
    currentPage.value = page;
  } catch (error) {
    ElMessage.error('加载评论失败');
  }
};

const canEdit = (comment) => {
  return user.value?.role === 'admin' || comment.reader_id === user.value?.reader_id;
};

const canDelete = (comment) => {
  return user.value?.role === 'admin' || comment.reader_id === user.value?.reader_id;
};

const handleEdit = (comment) => {
  editingComment.value = { ...comment };
  editDialogVisible.value = true;
};

const submitEdit = async () => {
  try {
    await request.put(`/reader/comments/${editingComment.value.comment_id}`, { content: editingComment.value.content });
    ElMessage.success('更新成功');
    editDialogVisible.value = false;
    fetchComments(currentPage.value);
  } catch (error) {
    ElMessage.error('更新失败');
  }
};

const handleDelete = (commentId) => {
  ElMessageBox.confirm('确定要删除这条评论吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const url = user.value?.role === 'admin' ? `/admin/comments/${commentId}` : `/reader/comments/${commentId}`;
      await request.delete(url);
      ElMessage.success('删除成功');
      fetchComments(currentPage.value);
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

const likeComment = async (comment) => {
  try {
    const response = await request.post(`/reader/comments/${comment.comment_id}/like`);
    comment.likes = response.likes;
  } catch (error) {
    ElMessage.error('点赞失败');
  }
};

onMounted(() => {
  fetchComments();
});
</script>

<style scoped>
.reviews-container {
  padding: 20px;
}
.comment-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  padding: 20px;
  margin-bottom: 20px;
}
.comment-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
.username {
  font-weight: bold;
  margin-left: 10px;
}
.novel-title {
  margin-left: 10px;
  color: #909399;
  font-size: 14px;
}
.comment-content {
  margin-bottom: 15px;
}
.comment-footer {
  display: flex;
  justify-content: flex-end;
}
</style>